package com.syf.config.swagger;


import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.configuration.ObjectMapperConfigured;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

/**
 * Swagger2 用做 API 文档的产出工具
 *
 * @ConfigurationProperties注解，主要是用来把properties或者yml配置文件转化为bean来使用,并从IOC容器中获取bean
 * @EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效
 *
 *  Swagger接口文档：
 *      http://localhost:8071/admin/swagger-ui.html
 *      http://localhost:8071/admin/doc.html
 */
@Configuration
@EnableSwagger2WebMvc  //springfox-swagger2 (2.10.5)版本才能使用该注解
@ConditionalOnProperty(name = "knife4j.enabled", matchIfMissing = true)  //配置文件中 knife4j.enabled = true,满足条件才注册bean
@EnableConfigurationProperties(SwaggerProperties.class) //把使用 @ConfigurationProperties 的类进行了一次注入
public class Knife4jConfiguration {
    //配置文件中Swagger信息映射实体
    private SwaggerProperties swaggerProperties;

    public Knife4jConfiguration(SwaggerProperties swaggerProperties) { //注入SwaggerProperties类
        this.swaggerProperties = swaggerProperties;
    }

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())  //api 信息的简介
                .select()
                //扫描Controller路径：swagger2:base-package: com.syf.controller   #
                .apis(RequestHandlerSelectors.basePackage("com.syf.controller")) //去扫描指定包下的文件(controller)
                .paths(PathSelectors.any()) //所有路径
                .build()
                .groupName("2.X版本");

        // 安全的配置
        docket.securitySchemes(securitySchemes()) // 安全规则
                .securityContexts(securityContexts()); // 安全配置的上下问

        return docket;
    }


    /**
     * api 信息的简介（构建 api文档的详细信息函数）
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact(swaggerProperties.getName(), swaggerProperties.getUrl(), swaggerProperties.getEmail()))
                .title(swaggerProperties.getTitle())  //"api文档"
                .description(swaggerProperties.getDescription()) //描述： "restful 风格接口"
                .version(swaggerProperties.getVersion())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .build();
    }

    /**
     * 安全模式，这里指定token通过Authorization头请求头传递
     */
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全的上下问
     *
     * @return
     */
//    private List<SecurityContext> securityContexts() {
//        return Arrays.asList(new SecurityContext(
//                Arrays.asList(new SecurityReference("Authorization", new AuthorizationScope[]{new AuthorizationScope("global", "accessResource")})),
//                PathSelectors.any()
//        ));
//    }

    /**
     * 安全上下文:
     * PathSelectors类的方法：
     *      Predicate<String> any():满足条件的路径，该断言总为true
     *      Predicate<String> none():不满足条件的路径,该断言总为false
     *      Predicate<String> regex(final String pathRegex):符合正则的路径
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))   //符合正则的路径
                        .build());
        return securityContexts;
    }

    /**
     * 默认的全局鉴权策略
     *
     * @return
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }


    /**
     * swagger支持 fastjson的 @JSONField (Json序列化映射)
     */
    @PostConstruct    //自定义初始化，启动器启动执行且只执行一次
    public void setObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        objectMapper.registerModule(module);

        objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {

            @Override
            public boolean isAnnotationBundle(Annotation ann) {
                if (ann.annotationType() == JSONField.class) {
                    return true;
                }
                return super.isAnnotationBundle(ann);
            }

            @Override
            public PropertyName findNameForSerialization(Annotated a) {
                PropertyName nameForSerialization = super.findNameForSerialization(a);
                if (nameForSerialization == null || nameForSerialization == PropertyName.USE_DEFAULT) {
                    JSONField jsonField = _findAnnotation(a, JSONField.class);
                    if (jsonField != null) {
                        return PropertyName.construct(jsonField.name());
                    }
                }
                return nameForSerialization;
            }

            @Override
            public PropertyName findNameForDeserialization(Annotated a) {
                PropertyName nameForDeserialization = super.findNameForDeserialization(a);
                if (nameForDeserialization == null || nameForDeserialization == PropertyName.USE_DEFAULT) {
                    JSONField jsonField = _findAnnotation(a, JSONField.class);
                    if (jsonField != null) {
                        return PropertyName.construct(jsonField.name());
                    }
                }
                return nameForDeserialization;
            }
        });

        ObjectMapperConfigured objectMapperConfigured = new ObjectMapperConfigured(applicationContext, objectMapper);
        applicationContext.publishEvent(objectMapperConfigured);
    }


}
